#!/bin/sh
#
# @license   http://www.gnu.org/licenses/gpl.html GPL Version 3
# @author    Ian Moore <imooreyahoo@gmail.com>
# @copyright Copyright (c) 2011 Ian Moore
#
# This file is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This file is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this file. If not, see <http://www.gnu.org/licenses/>.

set -e

. /etc/default/openmediavault
. /usr/share/openmediavault/scripts/helper-functions


# Nothing to do if service is not enabled
if [ "$(omv_config_get "//services/mysql/enable")" != "1" ]; then
	exit 0
fi

NEWPW=$(omv_config_get "//services/mysql/password" | sed -e "s/'/\\\'/g")

PWFD="/tmp/.openmediavault-mysql"
PWF="/tmp/.openmediavault-mysql/pw.$$"

[ -d ${PWFD} ] || /bin/mkdir ${PWFD}
/bin/chown mysql:mysql ${PWFD}
/bin/chmod 700 ${PWFD}
echo ''>${PWF}
/bin/chown mysql:mysql ${PWF}
/bin/chmod 400 ${PWF}

# Blank password? If you really want
if [ "${NEWPW}" = "" ]; then

cat <<EOF >> ${PWF}
UPDATE mysql.user SET Password = '' WHERE User='root';
FLUSH PRIVILEGES;
EOF

else

cat <<EOF >> ${PWF}
UPDATE mysql.user SET Password=PASSWORD('${NEWPW}') WHERE User='root';
FLUSH PRIVILEGES;
EOF

fi

cat <<EOF > /etc/mysql/conf.d/pw.cnf
[mysqld]
init-file = ${PWF}
EOF

/etc/init.d/mysql restart

/bin/rm -f /etc/mysql/conf.d/pw.cnf
/bin/rm -f ${PWF}
[ -d ${PWFD} ] && find ${PWFD} -type f -user mysql -exec rm {} \;
/bin/rmdir ${PWFD}

